'''
请设计一个函数，用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始，每一步可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格，那么该路径不能再次进入该格子。例如，在下面的3×4的矩阵中包含一条字符串“bfce”的路径（路径中的字母用加粗标出）。

[["a","b","c","e"],
["s","f","c","s"],
["a","d","e","e"]]

但矩阵中不包含字符串“abfb”的路径，因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后，路径不能再次进入这个格子。

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
'''

class Solution:
    def exist(self, board, word: str) -> bool:
        rows = len(board)
        cols = len(board[0])
        index = 0
        res = [False]
        pb = [[False]*cols for _ in range(rows)]
        def dfs(p,row,col,rows,cols,pb,index,word):
            if res[0] or index == len(word):
                res[0] =True
                return
            if row-1>=0:
                if p[row-1][col] == word[index] and not pb[row-1][col]:
                    pb[row-1][col] = True
                    dfs(p,row-1,col,rows,cols,pb,index+1,word)
                    pb[row-1][col] = False
            if row+1<rows:
                if p[row + 1][col] == word[index] and not pb[row + 1][col]:
                    pb[row + 1][col] = True
                    dfs(p, row + 1, col, rows, cols, pb, index + 1, word)
                    pb[row + 1][col] = False
            if col-1>=0:
                if p[row][col-1] == word[index] and not pb[row][col-1]:
                    pb[row][col-1] = True
                    dfs(p, row, col-1, rows, cols, pb, index + 1, word)
                    pb[row][col-1] = False
            if col+1<cols:
                if p[row][col+1] == word[index] and not pb[row][col+1]:
                    pb[row][col+1] = True
                    dfs(p, row, col+1, rows, cols, pb, index + 1, word)
                    pb[row][col+1] = False
        for i in range(rows):
            for j in range(cols):
                if board[i][j]==word[0]:
                    pb[i][j] = True
                    dfs(board,i,j,rows,cols,pb,index+1,word)
                    pb[i][j] = False
                    if res[0] == True:
                        return True
        else:
            return False


if __name__ == '__main__':
    # board = [["A","B","C","E"],
    #          ["S","F","C","S"],
    #          ["A","D","E","E"]]
    # board = [["a","b"],["c","d"]]
    board =[["a","a"]]
    word = "aaa"
    s = Solution()
    print(s.exist(board, word))